//
//  YHOauthVC.swift
//  XLWB
//
//  Created by key on 16/6/25.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class YHOauthVC: UIViewController {

    let web = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载视图
        loadSubView()
        
        //设置导航条
        setOauthNav()
        
        //设置导航条标题
        navigationItem.title = "登录"
    }
    
    //MARK: - 设置导航条
    @objc private func setOauthNav() {
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "loginClick")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "backPro")
        
    }
    
    //MARK: - 加载视图
    func loadSubView() {
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        
        let request = NSURLRequest(URL: url)
        
        web.loadRequest(request)
        
        view = web
        
        web.delegate = self
        
    }
    
    
    //MARK: - 返回上一界面
    @objc private func backPro() {
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    //MARK: - 自动填充
    @objc private func loginClick() {
        
        let jsString = "document.getElementById('userId').value='15727311891',document.getElementById('passwd').value='zxc111'"
        
//        let jsString = "document.getElementById('userId').value='13041075912',document.getElementById('passwd').value='Wall131026'"
        // js注入
        web.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
}

//MARK: - 设置代理
extension YHOauthVC : UIWebViewDelegate {
    
    
    //开始响应请求
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    //加载网页界面结束
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //加载出错
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    //将要加载的url
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取加载url的字符串对象
        let urlString = request.URL?.absoluteString
        
        //判断是否是想要拦截的url   如果加载url 不为空 并且 是以指定字符串开头的 就结继续往下执行
        guard let u = urlString where u.hasPrefix(REDIRECT_URI) else{
            
            return true
            
        }
        
        //关闭蒙版
        SVProgressHUD.dismiss()
        
        //获取加载的url的参数
        let queryStr = request.URL?.query
        
        //截取参数字符串
        let code = queryStr?.substringFromIndex("code=".endIndex)
        
        //调用方法 发送网络请求 获取token
        loadUserAccount(code!)

        //返回false 告诉系统加载到的url 自己处理了
        return false
        
        
    }
    
    
    
    //MARK: - 获取token
    func loadUserAccount(code: String) {
        
        //调用工具类 实现数据获取
        YHNetworkTool.sharedTool.oauthLoadUserAccount(code, success: { (request) -> () in
            
            //判断获取的数据是什么类型 是字典 执行判断代码块部分
            if let dataDict = request as? [String: AnyObject] {
                
                //数据转模型
                let userAccount = YHAccountModel(dict: dataDict)
                
                //调用方法 获取个人信息
                self.loadUserInfo(userAccount)
                
                
            }else {
                
                SVProgressHUD.showErrorWithStatus("网络数据加载错误")
                print("获取的数据不是字典-->")
            
            }
            
            
            
            }) { (error) -> () in
                
                //获取数据失败 打印错误信息
                print(error)
                
        }
        
        
        
    }
    
    
    //MARK: - 根据token参数获取个人信息
    func loadUserInfo(userAccount: YHAccountModel) {
        
        //调用工具类 实现数据获取
        YHNetworkTool.sharedTool.oauthLoadUserInfo(userAccount, success: { (request) -> () in
            
            //判断获取的数据是什么类型 是字典 执行判断代码块部分
            if let dataDict = request as? [String: AnyObject] {
                
                //获取到的数据转模型
                userAccount.screen_name = dataDict["screen_name"] as? String
                userAccount.avatar_large = dataDict["avatar_large"] as? String
                
                //把数据存入沙盒
                YHUserAccountTool.sharedUserAccountTool.saveUserAccount(userAccount)
                
                //关闭登陆控制器  跳转到欢迎界面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    //重新设置根控制器 为欢迎界面
                    let app = UIApplication.sharedApplication()
                    
                    app.keyWindow?.rootViewController = YHWelcomeVC()
                    
                    
                })
                
            }else {
                
                SVProgressHUD.showErrorWithStatus("网络数据加载错误")
                print("获取的数据不是字典-->")
                
            }
                
            
            
            }, failure: { (error) -> () in

                //获取数据失败 打印错误信息
                print(error)
                
        })
        
        
    }
    
    
    
}
